#include "qelib.h"


static qe_const_str usages[] = {
    "spif [options] [[--] args]",
    "spif [options]",
    QE_NULL,
};

static qe_ret action_probe_spif(qe_argparse *parser, qe_option *option)
{
    qe_spif_dev *dev = qe_spif_probe("flash", qe_option_string(option), QE_NULL);
    if (!dev) {
        qe_printf("probe flash failed\r\n");
    } else {
        qe_printf("probe flash success\r\n");
    }
    return qe_yield;
}

static qe_int read_status(qe_spi_dev *spi, qe_u8 *status)
{
	qe_u8 cmd = QE_SPIF_CMD_READ_SR;
	return qe_spi_send_recv(spi, &cmd, 1, status, 1);
}

// static qe_int is_spiflash_busy(const char *spidev)
// {
// 	qe_u8 status;
// 	qe_ret ret;
// 	struct qe_spi_device *spi;

// 	spi = (struct qe_spi_device *)qe_dev_find(spidev);
// 	if (!spi) {
// 		return -(qe_err_common);
// 	}

// 	ret = spi_flash_status(spi, &status);
// 	if (ret != 1) {
// 		return -1;
// 	}

// 	return status;
// }

static qe_ret action_read_status(qe_argparse *parser, qe_option *option)
{
    qe_u8 sr;
    qe_int n;
    qe_spi_dev *spi = (qe_spi_dev *)qe_dev_find(qe_option_string(option));
    if (!spi) {
        qe_printf("no %s\r\n", qe_option_string(option));
        return qe_yield;
    }

    n = read_status(spi, &sr);
    if (n < 0) {
        qe_printf("read status err:%d\r\n", n);
    } else {
        qe_printf("status %x\r\n", sr);
    }

    return qe_yield;
}

static qe_ret action_read_jedec_id(qe_argparse *parser, qe_option *option)
{
    qe_u8 cmd;
    qe_u8 data[3] = {0};
    qe_int n;
    
    qe_spi_dev *spi = (qe_spi_dev *)qe_dev_find(qe_option_string(option));
    if (!spi) {
        qe_printf("no %s\r\n", qe_option_string(option));
        return qe_yield;
    }

    cmd = QE_SPIF_CMD_JEDEC_ID;
	n = qe_spi_send_recv(spi, &cmd, 1, data, 3);
	if (n < 0) {
		qe_printf("read jedec id err:%d\r\n", n);
	} else {
        qe_printf("read jedec id %x %x %x\r\n", data[0], data[1], data[2]);
    }

    return qe_yield;
}

static void cmd_spif(int argc, char *argv[])
{
    qe_str name;
    qe_argparse parser;

    qe_option options[] = {
        QE_ACT_STRING('p', "probe", "probe spi flash",
            &name, QE_NULL, action_probe_spif),
		QE_ACT_STRING('s', "status", "read status",
            &name, QE_NULL, action_read_status),
		QE_ACT_STRING('i', "id", "read jedec id",
            &name, QE_NULL, action_read_jedec_id),
        QE_OPT_HELP('h', "--help", "spif help"),
        QE_OPT_END(),
    };

    qe_argp_init(&parser, options, usages,
    	"\nspif command.",
		"\nspif command.");

    qe_argp_parse(&parser, argc, (qe_const_str *)argv);
}
QE_SHELL_EXPORT_CMD_EXEC(spif, cmd_spif, spif commands);
